from Database import *


class Shelf:
    def __init__(self, shelf_id, initlist=()):
        self.db = Database('./database.db')

        if initlist == ():  # 读取模式
            print("读取模式")
            self.writemode = False
            self.idisvalid = True
            sql = 'SELECT * FROM shelves WHERE id="' + str(shelf_id) + '"'
            # print(shelf_id)
            rowshelf = self.db.fetchone(sql)
            if rowshelf:
                # print(rowshelf)
                rowshelf = list(rowshelf)
                # print(rowshelf)
                sql = 'SELECT id FROM shelves WHERE follow="' + str(shelf_id) + '"'

                rowfollow = self.db.fetchall(sql)
                # print(rowfollow)
                subs = []

                for row in rowfollow:
                    subs.append(row[0])
                rowshelf.append(subs)
                # print(rowshelf)
                # (id, name, type, follow, img, comment, [sub1,sub2,sub3,...])
                title = ('id', 'name', 'type', 'follow', 'img', 'comment', 'sub')
                initdict = dict(zip(title, rowshelf))
                # print(initdict)
                # {'id': 2, 'name': '22', 'type': 'shelf', 'follow': 22, 'img': None, 'comment': None, 'sub': [1, 3]}
                self.name = initdict['name']
                self.type = initdict['type']
                self.follow = initdict['follow']
                self.img = initdict['img']
                self.comment = initdict['comment']
                self.sub = initdict['sub']
                self.idisvalid = True
            else:
                self.idisvalid = False
        else:
            print("写入模式")
            self.writemode = True
            self.initlist = initlist
            # 写入模式的initlist格式   ('name', 'type', 'follow', 'img_name图片文件名', 'comment')

    def __str__(self):
        # print(b.name)
        # print(b.type)
        # print(b.follow)
        # print(b.img)
        # print(b.comment)
        # print(b.sub)
        if self.idisvalid:
            dict = {'name': self.name,
                    'type': self.type,
                    'follow': self.follow,
                    'img': self.img,
                    'comment': self.comment,
                    'sub': self.sub
                    }

            return "name: %(name)s\ntype: %(type)s\nfollow: %(follow)s\nimg: %(img)s\ncomment: %(comment)s\nsub: %(sub)s" % dict
        else:
            return False

    def commit(self, initlist=()):  # 提交到数据库
        if initlist == ():  # 读取模式下的提交 此时initlist是元组
            pass
        else:
            # 写入模式下的提交 此时initlist已被先行转为列表
            # 格式与初始化时一样 ('name', 'type', 'follow', 'img_name图片文件名', 'comment')
            self.initlist = list(self.initlist)
            # print(self.initlist[3])  #img_name
            try:
                with open('' + self.initlist[3], 'rb') as f:
                    img = f.read()
                    self.initlist[3] = img
            except FileNotFoundError as e:
                print(e)
                self.initlist[3] = None
                forcecommit = input('img file not found, continue to commit(y/n)?\n')
                if forcecommit == 'y':  # 强行提交
                    print("强行提交")
                    self.db.execute('INSERT INTO shelves (name, type, follow, img, comment) VALUES (?,?,?,?,?)',
                                    self.initlist)
                    return 'force commit'
                elif forcecommit == 'n':  # 取消提交
                    print("取消提交")
                    return "user cancel"
                # initlist is prepared(now it's a list)
            # 图片文件已找到 正常提交
            self.db.execute('INSERT INTO shelves (name, type, follow, img, comment) VALUES (?,?,?,?,?)', self.initlist)
            print(self.initlist)
            return 'normal commit'

        #  ('name', 'shelf', 2, img, 'comment')

        # self.db.execute('INSERT INTO shelves (name, type, follow, img, comment) VALUES (?,?,?,?,?)', inserttuple)[0]


if __name__ == '__main__':
    # 根据id取出数据库中的shelf并输出
    a = Shelf(22222222222)
    if a.idisvalid:
        print(a.type)
        print(a.name)
        print(a.type)
        print(a.follow)
        print(a.img)
        print(a.comment)
        print(a.sub)

    b = Shelf(5)
    if b.idisvalid:
        print(b.name)
        print(b.type)
        print(b.follow)
        print(b.img)
        print(b.comment)
        print(b.sub)
        print(b)

    # 新建一个shelf并存储到数据库
    # c = Shelf(False, ('name5', 'type', 'follow', input('drag img file here')[1:-1], 'comment'))
    # print(c.initlist)
    # print(c.commit(c.initlist))
